import datetime
import os
import random

import unicodedata
import yaml

import botpy
from botpy import logging
from botpy.ext.cog_yaml import read
from botpy.message import GroupMessage, C2CMessage
from src import mc, sr

test_config = read("./config.yaml")
_log = logging.get_logger()
image_path = "https://gitee.com/ChenQingShiMeng/qqbot/raw/master/src/image/"


def info():
    with open("src/cmd/config.txt", "r", encoding="utf-8") as f:
        lines = f.readlines()  # 读取所有行，返回一个列表
    modified_lines = [line for line in lines]
    # 将修改后的行内容合并为一个字符串
    content = ''.join(modified_lines)
    return content.rstrip()


def mc_pool():
    file = "src/mc/pool.txt"
    # 获取当前本地时间并格式化，省去秒
    local_time = datetime.datetime.now()
    formatted_time = local_time.strftime("%Y-%m-%d %H:%M")

    # 读取YAML文件，指定编码为utf-8
    with open("src/mc/pool.yaml", 'r', encoding='utf-8') as stream:
        data = yaml.safe_load(stream)
    if local_time > datetime.datetime.strptime(data['end_time'], "%Y-%m-%d %H:%M"):
        return "版本已更新，请更新卡池信息"
    mc.duration(formatted_time, data, file)
    mc.pool(local_time, data, file)

    with open(file, 'r', encoding='utf-8') as file:
        lines = file.readlines()  # 读取所有行，返回一个列表

    modified_lines = [line for line in lines]

    # 将修改后的行内容合并为一个字符串
    content = ''.join(modified_lines)
    return content.rstrip()


def update_mc(key, value):
    print(key, value)
    file = "src/mc/pool.yaml"
    return mc.update(file, key, value.replace('：', ': '))


def sr_pool():
    file = "src/sr/pool.txt"
    # 获取当前本地时间并格式化，省去秒
    local_time = datetime.datetime.now()
    # 读取YAML文件，指定编码为utf-8
    with open("src/sr/pool.yaml", 'r', encoding='utf-8') as stream:
        data = yaml.safe_load(stream)
    if local_time > datetime.datetime.strptime(data['end_time'], "%Y-%m-%d %H:%M"):
        # 将 mid_time 和 end_time 的时间增加 42 天
        mid_time = datetime.datetime.strptime(data['mid_time'], "%Y-%m-%d %H:%M")
        end_time = datetime.datetime.strptime(data['end_time'], "%Y-%m-%d %H:%M")

        # 增加 42 天
        mid_time += datetime.timedelta(days=42)
        end_time += datetime.timedelta(days=42)

        # 更新 YAML 文件中的时间
        data['mid_time'] = mid_time.strftime("%Y-%m-%d %H:%M")
        data['end_time'] = end_time.strftime("%Y-%m-%d %H:%M")

        # 将更新后的内容写回 YAML 文件
        with open("src/sr/pool.yaml", 'w', encoding='utf-8') as stream:
            yaml.safe_dump(data, stream, allow_unicode=True)

        return "版本已更新，请更新卡池信息"

    sr.pool()
    with open(file, 'r', encoding='utf-8') as file:
        lines = file.readlines()  # 读取所有行，返回一个列表

    modified_lines = [line for line in lines]

    # 将修改后的行内容合并为一个字符串
    content = ''.join(modified_lines)
    return content.rstrip()


def update_sr(key, value):
    print(key, value)
    return sr.update("src/sr/pool.yaml", key, value.replace('：', ': '))


# 获取本地目录下的随机图片文件名
def get_random_image_filename(directory):
    # 列出目录下的所有文件
    files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
    # 过滤出图片文件（可以根据需要扩展支持的图片格式）
    image_files = [f for f in files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp'))]
    if not image_files:
        raise FileNotFoundError("No image files found in the directory.")
    # 随机选择一个图片文件
    return random.choice(image_files)


# 获取随机图片的完整路径
def get_random_image_url():
    local_directory = "./src/image"  # 本地图片目录
    random_filename = get_random_image_filename(local_directory)
    return image_path + random_filename


def contains_chinese(name: str) -> bool:
    for char in name:
        if unicodedata.category(char) == 'Lo' and '\u4e00' <= char <= '\u9fff':
            return True
    return False


class MyClient(botpy.Client):
    async def on_ready(self):
        _log.info(f"robot 「{self.robot.name}」 on_ready!")

    # @猫猫
    @staticmethod
    async def on_group_at_message_create(message: GroupMessage):
        print(message)
        print('@猫猫', message.content)
        message_list = message.content.replace('/', '/').lstrip().split(' ')
        print(message_list)
        if "/使用简介" in message_list[0]:
            _log.info("开始输出功能菜单")
            await message.reply(content=info())
            _log.info("菜单信息输出结束")
        elif "/鸣潮卡池" in message_list[0]:
            _log.info("获取鸣潮卡池信息")
            print(mc_pool())
            await message.reply(content=mc_pool())
            _log.info("卡池信息输出结束")
        elif "/更新鸣潮" in message_list[0]:
            _log.info("开始更新鸣潮卡池信息")
            if len(message_list) == len(['/更新鸣潮', '上半卡池', '01-23', '09:59']):
                await message.reply(content=update_mc(message_list[1], message_list[2] + " " + message_list[3]))
            elif len(message_list) == len(['/更新鸣潮', '上半卡池', '01-23']):
                await message.reply(content=update_mc(message_list[1], message_list[2]))
            _log.info("更新结束")
        elif "/星铁卡池" in message_list[0]:
            _log.info("获取星铁卡池信息")
            print(sr_pool())
            await message.reply(content=sr_pool())
            _log.info("卡池信息输出结束")
        elif "/更新星铁" in message_list[0]:
            _log.info("开始更新星铁卡池信息")
            await message.reply(content=update_sr(message_list[1], message_list[2]))
            _log.info("更新结束")
        elif "/随机图片" in message_list[0]:
            if len(message_list) == 2 and message_list[1]=='sf':
                file_url = f'https://gitee.com/ChenQingShiMeng/qqbot/raw/master/src/sf/{random.randrange(0, 4)}.jpg'
            else:
                file_url = get_random_image_url()
            print(file_url)
            uploadMedia = await message._api.post_group_file(
                group_openid=message.group_openid,
                file_type=1,  # 文件类型要对应上，具体支持的类型见方法说明
                url=file_url  # 文件Url
            )

            # 资源上传后，会得到Media，用于发送消息
            await message._api.post_group_message(
                group_openid=message.group_openid,
                msg_type=7,  # 7表示富媒体类型
                msg_id=message.id,
                media=uploadMedia
            )
        elif "/指定" in message_list[0]:
            with open("src/name.yaml", 'r', encoding='utf-8') as stream:
                data = yaml.safe_load(stream)
            data['name'] = message_list[1]
            with open("src/name.yaml", 'w', encoding='utf-8') as f:
                yaml.dump(data, f, allow_unicode=True, sort_keys=False)
            await message.reply(content="指定更换成功")
        elif "神兵" in message.content or "神金" in message.content:
            with open("src/name.yaml", 'r', encoding='utf-8') as file:
                data = yaml.safe_load(file)
            name = data['name']
            if contains_chinese(name):
                print(f"'{name}' 包含中文字符")
                await message.reply(content=f"听不懂你在说什么")
            if name in ['chenqingshimeng', 'cqsm', 'csl', 'lwl', 'wl', '50', '40']:
                name = "sf"
            await message.reply(content=f'这说的是 {name} 吧')
        else:
            _log.info("@猫猫未指定功能")
            await message.reply(content=f"猫猫很不高兴为你服务")

    @staticmethod
    async def on_c2c_message_create(message: C2CMessage):
        # print(message)
        print(message.content)
        message_list = message.content.replace('/', '/').lstrip().split(' ')
        if "/使用介绍" in message_list[0]:
            _log.info("开始输出功能菜单")
            await message.reply(content=f"/鸣潮卡池\n")
            _log.info("菜单信息输出结束")
        elif "/鸣潮卡池" in message_list[0]:
            _log.info("获取鸣潮卡池信息")
            await message.reply(content=mc_pool())
            _log.info("卡池信息输出结束")
        elif "/更新鸣潮" in message_list[0]:
            _log.info("开始更新鸣潮卡池信息")
            if len(message_list) == len(['/更新鸣潮', '上半卡池', '01-23', '09:59']):
                await message.reply(content=update_mc(message_list[1], message_list[2] + " " + message_list[3]))
            elif len(message_list) == len(['/更新鸣潮', '上半卡池', '01-23']):
                await message.reply(content=update_mc(message_list[1], message_list[2]))
            _log.info("更新结束")
        elif "/星铁卡池" in message_list[0]:
            _log.info("获取星铁卡池信息")
            print(sr_pool())
            await message.reply(content=sr_pool())
            _log.info("卡池信息输出结束")
        elif "/更新星铁" in message_list[0]:
            _log.info("开始更新星铁卡池信息")
            await message.reply(content=update_sr(message_list[1], message_list[2]))
            _log.info("更新结束")
        elif "/随机图片" in message_list[0]:

            # 获取随机图片的完整 URL
            random_image_url = get_random_image_url()
            print(random_image_url)
            uploadMedia = await message._api.post_c2c_file(
                openid=message.author.user_openid,
                file_type=1,  # 文件类型为图片
                url=random_image_url  # 使用随机图片的 URL
            )

            # 资源上传后，会得到Media，用于发送消息
            await message._api.post_c2c_message(
                openid=message.author.user_openid,
                msg_type=7,  # 7表示富媒体类型
                msg_id=message.id,
                media=uploadMedia
            )
        else:
            _log.info("@猫猫未指定功能")
            await message.reply(content=f"oi")


if __name__ == "__main__":
    # 通过预设置的类型，设置需要监听的事件通道
    # intents = botpy.Intents.none()
    # intents.public_messages=True

    # 通过kwargs，设置需要监听的事件通道
    intents = botpy.Intents(public_messages=True, guild_messages=True)
    client = MyClient(intents=intents)
    client.run(appid=test_config["appid"], secret=test_config["secret"])
